/*
 * @Author: 追逐的娃 kangchao_php@163.com
 * @Date: 2024-07-04 09:19:31
 * @LastEditors: 追逐的娃 kangchao_php@163.com
 * @LastEditTime: 2025-01-08 20:45:00
 * @FilePath: \vue-project\src\permission.js
 * @Description: 
 * 
 */
import { router, addRoutes } from "@/router";
import { useUserStore } from "@/stores";
import { Message } from "@arco-design/web-vue";
import NProgress from 'nprogress'

//全局前置守卫
let hasGetInfo = false
router.beforeEach(async (to, from, next) => {
  const store = useUserStore()
  //加载条
  NProgress.start()
  //获取token
  const token = store.token
  /**
   * 判断是否存在token  
   * 存在:如果是登录页面那就跳到首页
   * 不存在：不是登陆页面跳转到登陆页面
   */
  //1、不存在token
  if (!token && to.path != '/login') {
    //提醒还没登录
    Message.info('您还没有登录');
    //条转到登录页面
    return next({ path: '/login' });
  }
  //2、token存在提醒不要重复登录
  if (token && to.path == '/login') {
    Message.info('您已登陆，请勿重复登录')
    //跳转到来的页面
    return next({ path: from.path ? from.path : '/' })
  }
  //如果用户登陆了获取用户权限
  let hasNewRoutes = false
  console.log(from,'from')
  if (token && !hasGetInfo) {
    //已经登录 但是没有获取用户信息===获取用户信心
    let { data } = await store.getUserInfo()
    hasGetInfo = true
    // 动态添加路由
    hasNewRoutes = addRoutes(data.data.menus)
  }
  // /设置页面标题
  let title = (to.meta.title ? to.meta.title : "") + "-弄个正经"
  document.title = title
  hasNewRoutes ? next(to.fullPath) : next()
});


//全局后置守卫(页面渲染完成)
router.afterEach((to, from) => {
  //关闭进度条
  NProgress.done()
});
